%debug if
if 0
clear,clf;
disp('Start reading image');
testimg = imread('flowers.jpeg');
% figure(1), imshow(testimg), title('testimg');
h_figure1=figure(1);
set(h_figure1, 'Name', 'Get RGB values of the image');
subplot(3,3,2), imshow(testimg), title('test image');
subplot(3,3,4), imshow(testimg(:,:,1)), title('R');
subplot(3,3,5), imshow(testimg(:,:,2)), title('G');
subplot(3,3,6), imshow(testimg(:,:,3)), title('B');

%convert it to L*a*b color space
load regioncoordinates;
nColors = 6;
sample_region = false([size(testimg,1) size(testimg,2) size(testimg,3)]);
for count = 1:nColors
    %select polygon region of interest
    sample_region(:,:,count) = roipoly(testimg, ...
                                       region_coordinates(:,1,count), ...
                                       region_coordinates(:,2,count));
end
%figure(2);
%imshow(sample_region(:,:,2)), title('sample region for red');

%convert rgb to lab
cform = makecform('srgb2lab');
lab_testimg = applycform(testimg, cform);

%show lab image elements
%set(h_figure2, 'Name', 'Show lab elements of lab color space');
%subplot(3,3,2), imshow(lab_testimg), title('test image');
subplot(3,3,7), imshow(lab_testimg(:,:,1)), title('L');
subplot(3,3,8), imshow(lab_testimg(:,:,2)), title('a');
subplot(3,3,9), imshow(lab_testimg(:,:,3)), title('b');

%calculates mean a and b value in each region
a = lab_testimg(:,:,2);
b = lab_testimg(:,:,3);
for count = 1:nColors
    color_marker(count,1) = mean2(a(sample_region(:,:,count)));
    color_marker(count,2) = mean2(b(sample_region(:,:,count)));
end

disp(sprintf('[%0.3f,%0.3f]',color_marker(2,1),color_marker(2,2)));


%classify each point using nearest neighbour
color_labels = 0:nColors-1;
a=double(a);
b=double(b);

for count = 1:nColors
    distance(:,:,count) = ((a-color_marker(count,1)).^2 + ...
                           (b-color_marker(count,2)).^2).^0.5;
end

[value, label] = min(distance, [], 3);
label = color_labels(label);
clear value distance;

%-->>debug end
end

%display result
rgb_label = repmat(label, [1 1 3]);
segmented_images = repmat(uint8(0),[size(testimg), nColors]);

for count = 1:nColors
  color = testimg;
  color(rgb_label ~= color_labels(count)) = 0;
  segmented_images(:,:,:,count) = color;
end

imshow(segmented_images(:,:,:,2)), title('red objects');
